package com.hunantv.mglive.widget.versionupdate;

import android.accounts.NetworkErrorException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.config.VersionModel;
import com.hunantv.mglive.utils.Toast;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class VersionUpdate {
    private Context mContext;
    private Dialog mDialog;
    private onButtonClickListener mListener;

    private ProgressBar mProgress;  //进度条
    private LinearLayout mBtnLayout; //底部的两个按钮层
    private VersionModel model;
    private String strPath;
    private int progress; //下载进度
    private static final int DOWNLOADING = 1; //表示正在下载
    private static final int DOWNLOADED = 2; //下载完毕
    private static final int DOWNLOAD_FAILED = 3; //下载失败

    public VersionUpdate(Context context) {
        setView(context);
    }

    private void setView(Context context) {
        mContext = context;
    }

    public void updateApp(VersionModel m) {
        model = m;
        View mView = LayoutInflater.from(mContext).inflate(R.layout.verupgrade_dailog_view, null);
        ImageView ivHead = (ImageView) mView.findViewById(R.id.iv_update_head_image);
        Glide.with(mContext).load(R.drawable.update_head_image).into(ivHead);
        TextView tvTitle = (TextView) mView.findViewById(R.id.tv_update_title);
        tvTitle.setText(model.getTitle() + "");

        TextView tvDes = (TextView) mView.findViewById(R.id.tv_update_des);
        String des = model.getDesc().replace("|", "\n");
        tvDes.setText(des);
        mProgress = (ProgressBar) mView.findViewById(R.id.download_progress);
        mBtnLayout = (LinearLayout) mView.findViewById(R.id.ll_update_btn);

        Button btnCancel = (Button) mView.findViewById(R.id.btn_notify_dialog_cancel);
        if (model.getAlert().equals("1")) { //强制升级
            btnCancel.setVisibility(View.GONE);
        }

        mView.findViewById(R.id.btn_notify_dialog_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onSure();
                }
                beginDownload();
                //mDialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                if (mListener != null) {
                    mListener.onCancel();
                }
            }
        });
        mDialog = new AlertDialog.Builder(mContext).setView(mView).create();
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnKeyListener(keylistener);
        mDialog.show();
    }

    public void setOnButtonClickListener(onButtonClickListener l) {
        mListener = l;
    }

    public interface onButtonClickListener {

        void onSure();

        void onCancel();
    }

    private void beginDownload() {
        mProgress.setVisibility(View.VISIBLE);
        mProgress.setProgress(0);
        mBtnLayout.setVisibility(View.GONE);
        downloadAPK();
    }

    /**
     * 下载apk的线程
     */
    public void downloadAPK() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(model.getAppUrl());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();

                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    strPath = Environment.getExternalStoragePublicDirectory("/download/").getAbsolutePath() + "/mglive.apk";
                    File file = new File(Environment.getExternalStoragePublicDirectory("/download/").getAbsolutePath());
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    String apkFile = strPath;
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);

                    int count = 0;
                    byte buf[] = new byte[1024];

                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        //更新进度
                        mHandler.sendEmptyMessage(DOWNLOADING);
                        if (numread <= 0) {
                            //下载完成通知安装
                            mHandler.sendEmptyMessage(DOWNLOADED);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (true); //点击取消就停止下载.

                    fos.close();
                    is.close();

                } catch (Exception e) {
                    mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 更新UI的handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOADED:
                    installAPK();

                    break;
                case DOWNLOAD_FAILED:
                    Toast.makeText(mContext, "下载升级包失败，请稍候再试", Toast.LENGTH_LONG).show();

                    mProgress.setVisibility(View.GONE);
                    mProgress.setProgress(0);
                    mBtnLayout.setVisibility(View.VISIBLE);

                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 下载完成后自动安装apk
     */
    public void installAPK() {
        File apkFile = new File(strPath);
        if (!apkFile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(intent);

        android.os.Process.killProcess(android.os.Process.myPid());    //获取PID
        System.exit(0);   //常规java、标准退出法，返回值为0代表正常退出
    }

    DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            return keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0;
        }
    };

    /*
    private void beginDownload(){
        downloadManager = (DownloadManager) MaxApplication.getApp().getSystemService(MaxApplication.getApp().DOWNLOAD_SERVICE);
        //开始下载
        Uri resource = Uri.parse(encodeGB(model.getAppUrl()));
        DownloadManager.Request request = new DownloadManager.Request(resource);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);
        //设置文件类型
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(model.getAppUrl()));
        request.setMimeType(mimeString);
        //在通知栏中显示
        request.setShowRunningNotification(true);
        request.setVisibleInDownloadsUi(true);
        //sdcard的目录下的download文件夹
        request.setDestinationInExternalPublicDir("/download/", "mglive.apk");
        strPath = Environment.getExternalStoragePublicDirectory("/download/").getAbsolutePath() + "/mglive.apk";

        request.setTitle("芒果直播");
        try {
            downID = downloadManager.enqueue(request);
        }catch(Exception e){
            Toast.makeText(mContext,"请启动系统的“下载管理器”，以便于升级。",1000).show();
            return;
        }
        MaxApplication.getApp().registerReceiver(receiverDownload, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

*/
//
//    /**
//     * 如果服务器不支持中文路径的情况下需要转换url的编码。
//     *
//     * @param string
//     * @return
//     */
//    public String encodeGB(String string) {
//        //转换中文编码
//        String split[] = string.split("/");
//        for (int i = 1; i < split.length; i++) {
//            try {
//                split[i] = URLEncoder.encode(split[i], "GB2312");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            split[0] = split[0] + "/" + split[i];
//        }
//        split[0] = split[0].replaceAll("\\+", "%20");//处理空格
//        return split[0];
//    }

//    private BroadcastReceiver receiverDownload = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            queryDownloadStatus();
//        }
//    };
//
//    private void queryDownloadStatus() {
//        DownloadManager.Query query = new DownloadManager.Query();
//        query.setFilterById(downID);
//        Cursor c = downloadManager.query(query);
//        if(c.moveToFirst()) {
//            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
//            switch(status) {
//                case DownloadManager.STATUS_PAUSED:
//                    Log.v("down", "STATUS_PAUSED");
//                case DownloadManager.STATUS_PENDING:
//                    Log.v("down", "STATUS_PENDING");
//                case DownloadManager.STATUS_RUNNING:
//                    //正在下载，不做任何事情
//                    Log.v("down", "STATUS_RUNNING");
//                    break;
//                case DownloadManager.STATUS_SUCCESSFUL:
//                    //完成
//                    Intent install = new Intent(Intent.ACTION_VIEW);
//
//                    Uri downloadFileUri = Uri.parse("file://" + strPath);
//                    install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
//                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    MaxApplication.getApp().startActivity(install);
//                    break;
//                case DownloadManager.STATUS_FAILED:
//                    break;
//            }
//        }
//    }
}
